/*******************************************************************/
/* @ All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.        */
/*                                                                 */
/*  NAME      = sip_core.c                                         */
/*  NOTE      =                                                    */
/*  DATE      = 2015/07/07 by songbb                               */
/*******************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>

#include "frcomm.h"
#include "frstr.h"
#include "frhash2.h"
#include "frmem.h"
#include "frlog.h"
#include "frsutl.h"
#include "frreport_comm.h"

#include "conntrack.h"
#include "frct_comm.h"
#include "frversion.h"

#include "sip_comm.h"
#include "sip_core.h"
#include "sip_header.h"
#include "sip_packet.h"
#include "sip_req.h"
#include "sip_resp.h"

#if APM_SIP_DBG
/* 模块全局变量：出错的包的个数 */
FR_STATIC unsigned long long g_ull_sip_error_nums = 0LL;
/* 模块全局变量：未正确解析的分片包的个数 */
FR_STATIC unsigned long long g_ull_sip_unfinshed_fragmented_packets = 0LL;
#endif

/*******************************************************************************
*  FUNC     :  累计未正确解析的包个数
*  ARGS     :  *p_st_sess                           (SIP私有的session)
*  RTN      :
*  NOTE     :
*******************************************************************************/
FR_STATIC void __sip_add_error_nums(L7session_sip *p_st_sess)
{
#if APM_SIP_DBG
    g_ull_sip_error_nums++;
#endif
    if (p_st_sess != NULL)
        p_st_sess->ull_error_nums++;
    return;
}

/*******************************************************************************
*  FUNC     :  累计未正确解析的分片包个数
*  ARGS     :  *p_st_sess                           (SIP私有的session)
*  RTN      :
*  NOTE     :
*******************************************************************************/
void sip_core_add_unfinshed_fragmented_packets(L7session_sip *p_st_sess)
{
#if APM_SIP_DBG
    g_ull_sip_unfinshed_fragmented_packets++;
#endif
    if (p_st_sess != NULL)
        p_st_sess->ull_unfinshed_fragmented_packets++;
    return;
}

/*******************************************************************************
*  FUNC     :  SIP Session初始化
*  ARGS     :  *p_st_session                            (L7层session信息)
*  RTN      :  0                                        (FR_SUCC)
*              1                                        (FR_FAIL)
*  NOTE     :
*******************************************************************************/
FR_STATIC int __sip_private_session_init(L7_session *p_st_session)
{
    SIP_PRINT_INFO("session init\n");
    L7session_sip_private *p_st_sip_private = NULL;      // SIP的私有信息
    L7session_sip *p_st_sip_sess = NULL;                 // SIP的私有session信息
    L7_sip_packet *p_st_sip_packet = NULL;               // SIP格式的packet包
    Frhash_header *p_hash_stmt = NULL;                   // SIP的statement信息结构

    // 1. 初始化SIP的私有session信息
    if ((p_st_sip_sess = (L7session_sip *) frmalloc(sizeof(L7session_sip))) == NULL)
    {
        SIP_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_sip_sess, 0x00, sizeof(L7session_sip));

    // 2. 初始化SIP格式的packet包
    if ((p_st_sip_packet = (L7_sip_packet *) frmalloc(sizeof(L7_sip_packet))) == NULL)
    {
        SIP_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_sip_packet, 0x00, sizeof(L7_sip_packet));
    if (sip_init_packet(p_st_sip_packet) != FR_SUCC)
        goto error;

    // 3. 初始化statement hash
    if ((p_hash_stmt = (Frhash_header *) frmalloc(sizeof(Frhash_header))) == NULL)
    {
        SIP_MALLOCK_ERR;
        goto error;
    }
    memset(p_hash_stmt, 0x00, sizeof(Frhash_header));
    if (frhash2_create(p_hash_stmt, APM_SIP_HASH_SIZE) != FR_SUCC)
    {
        SIP_FRLOG_ERROR("frhash2_create fail");
        goto error;
    }

    // 4. 创建和初始化SIP的私有信息
    if ((p_st_sip_private = (L7session_sip_private *) frmalloc(sizeof(L7session_sip_private))) == NULL)
    {
        SIP_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_sip_private, 0x00, sizeof(L7session_sip_private));
    p_st_sip_private->p_st_sess = p_st_sip_sess;
    p_st_sip_private->p_st_sip_packet = p_st_sip_packet;
    p_st_sip_private->p_st_session = p_st_session;
    p_st_sip_private->p_hash_stmt = p_hash_stmt;

    // 5. 设置L7_session的p_session_private信息
    frct_set_session_private(p_st_session, (void *)p_st_sip_private);

    return FR_SUCC;
error:
    frhash2_free2(p_hash_stmt, sip_stmt_node_free);
    sip_free((void **) &p_st_sip_private);
    return FR_FAIL;
}

/*******************************************************************************
*  FUNC     :  分析数据方向
*  ARGS     :  ui_msgcode                               (MsgCode)
*  RTN      :  0x00                                     (FR_DIRECT_UNKNOWN)
*              0x02                                     (FR_DIRECT_SRV2CLIENT)
*              0x03                                     (FR_DIRECT_CLIENT2SRV)
*  NOTE     :
*******************************************************************************/
FR_STATIC int __sip_analyze_direct(Apm_packet *p_st_packet)
{
    SIP_PRINT_INFO("__sip_analyze_direct\n");
    int i_is_req;
    if (sip_analyze_header(p_st_packet->p_payload, p_st_packet->ui_payload_len, &i_is_req, NULL, NULL, NULL) != FR_SUCC)
    {
        SIP_PRINT_FATAL("unknown\n");
        return FR_DIRECT_UNKNOWN;
    }

    if (i_is_req == FR_YES)
    {
        SIP_PRINT_FATAL("client to server\n");
        return FR_DIRECT_CLIENT2SRV;
    }
    else
    {
        SIP_PRINT_FATAL("server to client\n");
        return FR_DIRECT_SRV2CLIENT;
    }
}

/*******************************************************************************
*  FUNC     :  判断当前数据链路是否是SIP协议的
*  ARGS     :  *p_st_conn                           (ct信息)
*           :  *p_st_packet                        (协议分析入力数据)
*  RTN      :  参照module.h中APM_L7_IS_的定义
*  NOTE     :
*******************************************************************************/
int sip_detect(Conntrack *p_st_conn
            , Apm_packet *p_st_packet)
{
    SIP_PRINT_INFO("sip_detect\n");
    int i_analyzed_direct = 0;

    if(p_st_packet == NULL || p_st_packet->p_payload == NULL || p_st_packet->ui_payload_len == 0 || p_st_conn==NULL)
        return APM_L7_IS_NO;

#if APM_SIP_DBG
    char arr_ip_src[56], arr_ip_dst[56];
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->dst_ip));
    SIP_PRINT_TIMEVAL("PacketIn", p_st_packet->st_timestamp);
    SIP_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] Length:[%u]\n", arr_ip_src, p_st_packet->src_port, arr_ip_dst, p_st_packet->dst_port, p_st_packet->ui_payload_len);
#endif

    int i_ret;
    i_ret = sip_analyze_header(p_st_packet->p_payload, p_st_packet->ui_payload_len, NULL, NULL, NULL, NULL);
    if (i_ret == FR_SUCC)
    {
        // 设置方向
        if (p_st_packet->i_direction == FR_DIRECT_UNKNOWN || frct_get_direct_known(p_st_conn) == FR_DIRECT_UNKNOWN)
        {
            i_analyzed_direct = __sip_analyze_direct(p_st_packet);
            if (i_analyzed_direct == FR_DIRECT_CLIENT2SRV)
            {
                if (frcap_set_cs_srv(p_st_conn, p_st_packet->dst_ip, p_st_packet->dst_port) != FR_SUCC)
                    return APM_L7_IS_UNKNOWN;
            }
            else if (i_analyzed_direct == FR_DIRECT_SRV2CLIENT)
            {
                if (frcap_set_cs_srv(p_st_conn, p_st_packet->src_ip, p_st_packet->src_port) != FR_SUCC)
                    return APM_L7_IS_UNKNOWN;
            }
            else
            {
                SIP_PRINT_EMERG("Can not analyze direction\n");
                return APM_L7_IS_UNKNOWN;
            }
        }
    }

    if (i_ret == FR_FAIL)
    {
        SIP_PRINT_ERR("detect unknown\n\n");
        return APM_L7_IS_UNKNOWN;
    }
    else
    {
        SIP_PRINT_ERR("detect yes\n\n");
        return APM_L7_IS_YES;
    }
}

/*******************************************************************************
*  FUNC     :  SIP协议解析
*  ARGS     :  *p_st_conn                           (ct信息)
*           :  *p_analyze_in                        (协议分析入力数据)
*           :  *p_st_hash_report                    (保存Frreport_data)
*  RTN      :  参照module.h中APM_L7_ANALYZE_的定义
*  NOTE     :
*******************************************************************************/
int sip_analyze(Conntrack *p_st_conn
                , Apm_packet *p_analyze_in
                , Frhash_header *p_st_hash_report)
{
    SIP_PRINT_INFO("sip_analyze\n");
    L7_session *p_st_session = NULL;
    L7session_sip_private *p_st_session_private = NULL;
    L7session_sip *p_st_sess = NULL;
    L7_sip_packet *p_st_sip_packet = NULL;
    int i_unfragmented_ret = 0;
    char arr_ip_src[56], arr_ip_dst[56];
    int i_analyze_ret = APM_L7_ANALYZE_FAIL;

    if(p_st_conn == NULL || p_analyze_in == NULL
        || p_st_hash_report == NULL)
        return APM_L7_ANALYZE_FAIL;

    p_st_session = frct_get_session(p_st_conn);
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_analyze_in->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_analyze_in->dst_ip));

    SIP_PRINT_TIMEVAL("PacketIn", p_analyze_in->st_timestamp);
    SIP_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] SessionID:[%s]\n", arr_ip_src, p_analyze_in->src_port, arr_ip_dst, p_analyze_in->dst_port, p_st_session->arr_session_id);

    /*
    * 如果入力p_analyze_in是FIN包, 说明本次connection结束,
    * 释放本次session信息. 如果入力p_analyze_in是SYN包,说明新的
    * connection开始了, 释放上次可能残留的session信息
    */
    if (p_analyze_in->em_analyz_cmd == FRANALYZ_CMD_FIN || p_analyze_in->em_analyz_cmd == FRANALYZ_CMD_SYN)
    {
        if (p_analyze_in->em_analyz_cmd == FRANALYZ_CMD_SYN)
            SIP_PRINT_INFO("SYN PACKET\n");
        else if (p_analyze_in->em_analyz_cmd == FRANALYZ_CMD_FIN)
            SIP_PRINT_INFO("FIN PACKET\n");
        if (p_st_session->p_session_private != NULL)
        {
            sip_session_destory(p_st_session->p_session_private);
            p_st_session->p_session_private = NULL;
        }
        SIP_PRINT("### i_analyze_ret:[%d]\n\n", APM_L7_ANALYZE_SUCC);
        return APM_L7_ANALYZE_SUCC;
    }

    // 本次链路的第一个有效packet包,创建链路
    if (p_st_session->p_session_private == NULL)
    {
        // 初始化SIP的session数据
        if (__sip_private_session_init(p_st_session) != FR_SUCC)
            goto sip_analyze_fail;

        // 设置session uuid
        fruuid(p_st_session->arr_session_id);
    }

    if (p_analyze_in->i_direction != FR_DIRECT_CLIENT2SRV && p_analyze_in->i_direction != FR_DIRECT_SRV2CLIENT)
    {
        SIP_PRINT("unknown direction, src["KLIMEGREEN"%s:%d"RESET"], dest["KLIMEGREEN"%s:%d"RESET"]\n",
                  arr_ip_src,
                  p_analyze_in->src_port,
                  arr_ip_dst,
                  p_analyze_in->dst_port);
        goto sip_analyze_fail;
    }

    p_st_session_private = (L7session_sip_private *) frct_get_session_private(p_st_session);
    p_st_sess = p_st_session_private->p_st_sess;
    p_st_sip_packet = p_st_session_private->p_st_sip_packet;

    i_unfragmented_ret = sip_packet_unfragment(p_st_sess, p_analyze_in, p_st_sip_packet);
    if (i_unfragmented_ret == APM_SIP_CHECK_FRAGMENT_NEED_NEXT_PACKET)
        goto sip_analyze_todo;
    else if (i_unfragmented_ret == APM_SIP_CHECK_FRAGMENT_ERROR)
        goto sip_analyze_fail;

    if (p_st_sip_packet->i_is_sip_req == FR_YES)
    {
        SIP_PRINT("client["KLIMEGREEN"%s:%d"RESET"] to server["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] ->>>>>>>>>>>>>>>>>>>>>>>\n",
                  arr_ip_src,
                  p_analyze_in->src_port,
                  arr_ip_dst,
                  p_analyze_in->dst_port,
                  p_analyze_in->ui_payload_len);
        if (sip_analyze_req(p_st_conn, p_st_sess, p_st_sip_packet, p_st_hash_report, p_analyze_in) != FR_SUCC)
            goto sip_analyze_fail;
        i_analyze_ret = APM_L7_ANALYZE_SET_REQ(APM_L7_ANALYZE_SUCC);
        goto sip_analyze_success;
    }
    else
    {
        SIP_PRINT("server["KLIMEGREEN"%s:%d"RESET"] to client["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] <<<<<<<<<<<<<<<<<<<<<<<-\n",
                  arr_ip_src,
                  p_analyze_in->src_port,
                  arr_ip_dst,
                  p_analyze_in->dst_port,
                  p_analyze_in->ui_payload_len);
        if (sip_analyze_resp(p_st_conn, p_st_sess, p_st_sip_packet, p_st_hash_report) != FR_SUCC)
            goto sip_analyze_fail;
        i_analyze_ret = APM_L7_ANALYZE_SET_RESP(APM_L7_ANALYZE_SUCC);
        goto sip_analyze_success;
    }

sip_analyze_todo:
    SIP_PRINT("### i_analyze_ret todo:[%d]\n\n", APM_L7_ANALYZE_TODO);
    return APM_L7_ANALYZE_TODO;

sip_analyze_success:
    sip_init_packet(p_st_sip_packet);
    SIP_PRINT("### i_analyze_ret success:[%d]\n\n", i_analyze_ret);
    return i_analyze_ret;

sip_analyze_fail:
    if (sip_packet_is_in_fragment(p_st_sip_packet))
    {
        if (bytebuff_setPosition(p_st_sip_packet->p_st_packet, 0) != FR_SUCC)
        {
            p_st_sip_packet->fragment_state = APM_SIP_FRAGMENT_INIT;
            return APM_L7_ANALYZE_FAIL;
        }
        goto sip_analyze_todo;
    }
    else
    {
        __sip_add_error_nums(p_st_sess);
        SIP_PRINT_PACKET("error packet", p_st_sip_packet);
        sip_init_packet(p_st_sip_packet);
    }

    SIP_PRINT_EMERG("### i_analyze_ret fail:[%d]\n\n", APM_L7_ANALYZE_FAIL);
    return APM_L7_ANALYZE_FAIL;
}

/*******************************************************************************
*  FUNC     :  释放 L7session_sip
*  ARGS     :  **pp_st_session              (L7session_sip)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __sip_destroy_session(L7session_sip **pp_st_session)
{
    if (pp_st_session == NULL || *pp_st_session == NULL)
        return;

    sip_free((void **) &(*pp_st_session)->p_server);
    sip_free((void **) pp_st_session);
    return;
}

/*******************************************************************************
*  FUNC     :  释放 L7_sip_packet
*  ARGS     :  **pp_st_sip_packet              (L7_sip_packet)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __sip_destroy_packet(L7_sip_packet **pp_st_sip_packet)
{
    if (pp_st_sip_packet == NULL || *pp_st_sip_packet == NULL)
        return;

    L7_sip_packet *p_st_sip_packet = *pp_st_sip_packet;
    bytebuff_free(&(p_st_sip_packet->p_st_packet));
    sip_free((void **) &(p_st_sip_packet->p_req_method));
    sip_free((void **) pp_st_sip_packet);
    return;
}

/*******************************************************************************
*  FUNC     :  释放 L7_sip_stmt
*  ARGS     :  *p_hash_stmt              (Frhash_header)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __sip_destroy_stmt(Frhash_header *p_hash_stmt)
{
    frhash2_free2(p_hash_stmt, sip_stmt_node_free);
}

/*******************************************************************************
*  FUNC     :  释放SIP private数据
*  ARGS     :  *p_st_session_private_in                 (SIP的私有信息)
*  RTN      :  0                                        (FR_SUCC)
*              1                                        (FR_FAIL)
*  NOTE     :
*******************************************************************************/
int sip_session_destory(void *p_st_session_private_in)
{
    SIP_PRINT(KBLUE "\nsip_session_destory run\n" RESET);
    if (p_st_session_private_in == NULL)
        return FR_SUCC;

    L7session_sip_private *p_st_private = (L7session_sip_private *) p_st_session_private_in;

    __sip_destroy_session(&(p_st_private->p_st_sess));

    __sip_destroy_packet(&(p_st_private->p_st_sip_packet));

    __sip_destroy_stmt(p_st_private->p_hash_stmt);


    sip_free((void **) &p_st_private);

    SIP_PRINT_INFO("leave sip_session_destory\n");
    return FR_SUCC;
}
